<?php

namespace app\admin\controller\wdgroup;

use app\common\controller\Backend;
use think\Db;
class Wdocument extends Backend
{
    protected $model = null;
    protected $categoryModel = null;
    protected $noNeedRight = [];
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Wdocument');
        $this->categoryModel = model('Wdcate');
        $category = $this->categoryModel->where('status', 'normal')->where('pid',0)->order('weigh', 'desc')->select();
        $this->view->assign('category', $category);
        $categoryList = $this->categoryModel->where('status', 'normal')->where('pid','>',0)->order('weigh', 'desc')->select();
        $this->view->assign('categoryList', $categoryList);
    }
    
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['category','user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $categoryNames = \think\Db::name('wdocument_category')
                    ->alias('dc')
                    ->join('wd_wdcate c', 'dc.wdcate_id = c.id')
                    ->where('dc.wdocument_id', $v->id)
                    ->column('c.name');
                $v->categorys = $categoryNames?implode(',', $categoryNames):"";
                
            }
            
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
        }
        return $this->view->fetch();
    }
    
    
    
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            Db::startTrans();

            try {
                $tags = $params['tags'];
                unset($params['tags']); 
                $row->validate('common/Wdocument.edit')->allowField(true)->save($params);
                $docCate = [];
                foreach ($tags as $value) {
                    $docCate[] = ['wdocument_id'=>$row->id,'wdcate_id'=>$value];
                }
                Db::name('WdocumentCategory')->where('wdocument_id', $ids)->delete();
                Db::name('WdocumentCategory')->insertAll($docCate);
                $document = $row->toArray();

                $document['doc_id'] = $document['id'];
                unset($document['id']);
                unset($document['status_text']);
                Db::name('Document')->where('doc_id', $ids)->where('type','wd')->update($document);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $row['tags'] = Db::name('WdocumentCategory')->where('wdocument_id', $ids)->column('wdcate_id');
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    
    public function del($ids = '')
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    public function multi($ids = '')
    {
        $ids = $ids ? $ids : $this->request->param('ids');
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post('params'), $values);
                $values = array_intersect_key($values, array_flip(['status', 'flag']));
                if ($values) {
                    $count = $this->model->where('id', 'in', $ids)->update($values);
                    if ($count) {
                        $this->success();
                    }
                }
                $this->error(__('Operation failed'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}